package org.abettor.util.struts2;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

/**
 * 日期转换类，用于解决Linux下Chrome浏览器日期向后台传递的类型转换bug
 * @author abettor.org
 *
 */
public class DateConverter extends StrutsTypeConverter
{
	private static List<String> patterns = new ArrayList<String>();
	static
	{
		patterns.add("yyyy-MM-dd HH:mm:ss");
		patterns.add("yyyy-MM-dd");
		patterns.add("HH:mm:ss");
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Object convertFromString(Map context, String[] value, Class toType)
	{
		if(value == null || value.length <= 0)
		{
			return null;
		}

		if(toType == null || ! toType.getName().equals(Date.class.getName()))
		{
			return null;
		}

		String input = value[0];
		for(String pattern : patterns)
		{
			SimpleDateFormat sdf = new SimpleDateFormat(pattern);
			try
			{
				return sdf.parse(input);
			}
			catch (ParseException e)
			{
				//一个一个的尝试，不行就下一个
				continue;
			}
		}

		return null;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public String convertToString(Map context, Object value)
	{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format((Date) value);
	}
}
